import threading
import logging

user_list: dict[str, list] = dict()
user_list_lock = threading.Lock()

logger = logging.getLogger('mylogger')

# 用于获取锁的装饰器，可自动获取以及释放锁
def acquire_list_lock(func):
    def wrapper(*args, **kw):
        user_list_lock.acquire()
        res = func(*args, **kw)
        user_list_lock.release()
        return res

    return wrapper


@acquire_list_lock
def add_user(room_name, user_info):
    if room_name not in user_list:
        user_list[room_name] = [user_info]
    else:
        user_list[room_name].append(user_info)
    logger.info(user_list)


@acquire_list_lock
def remove_user(room_name, user_info):
    user_list[room_name].remove(user_info)
    if len(user_list[room_name]) == 0:
        user_list.pop(room_name)


@acquire_list_lock
def get_room_users(room):
    return user_list.get(room, []) # 提供默认值，以防room被删除后的调用异常


@acquire_list_lock
def get_rooms_status():
    res: list[dict] = list()
    for key, value in user_list.items():
        res.append({'name': key, 'userCount': len(value)})
    return {'list': res}
